require('./index.less');

import $ from 'jquery';
var ticket_list_data = { "id": "1", "jsonrpc": "2.0", "method": "getGroupTicketTypes", "params": {} };
var pay_data = {};
var ticketdata = $.ajax({
    type: "post",
    contentType: "application/json;charset=utf-8",
    url: "/api/ticketApi",
    dataType: "json",
    data: JSON.stringify(ticket_list_data),
});
ticketdata.then(function(res) {
    for (var i = 0; i < res.result.body.length; i++) {
        var ticket_list_html = $("#ticket_list").html();
        var tdata = res.result.body[i];
        var conReg = /(?:\{)(\w*)(?:\})/g;
        var source = ticket_list_html.replace(conReg, function(node, key) {
            return tdata[key];
        });
        $(".ticket_list").append(source);
    }
    var ticket_buy_html = $("#button-box").html();
    // var conReg = /(?:\{)(\w*)(?:\})/g;
    // var source_buy = ticket_buy_html.replace(conReg, function(node, key) {
    //     return tdata[key];
    // });
    $(".button-box").append(ticket_buy_html);
    var button = $(".push-select");
    var button = $(".push-select");
    for (var s = 0; s < button.length; s++) {
        (function(s) {
            button[s].onclick = function() {
                var ticket_choice_html = $("#ticket_choice").html();
                var chdata = {}
                chdata.code = $(this).parent().prevAll(".code").html();
                chdata.name = $(this).parent().prevAll(".name").html();
                chdata.price = $(this).parent().prevAll(".price").html();
                chdata.id = $(this).parent().prevAll(".id").html()
                chdata.number = "1";
                var conReg = /(?:\{)(\w*)(?:\})/g;
                var source = ticket_choice_html.replace(conReg, function(node, key) {
                    return chdata[key];
                });
                if ($(".ticket_choice").children("tr.ticket_" + chdata.id).length == "0") {
                    if (chdata.code == "etp") {
                        $(".ticket_choice").show().append(source);
                        $(".etp").children(".nameid").html("");
                    } else {
                        $(".ticket_choice").show().append(source);
                    }
                } else if ($(".ticket_choice").children("tr.ticket_" + chdata.id).length > "0") {
                    document.getElementById("number_" + chdata.id + "").innerHTML++
                };
                var p = chdata.price;
                var n = $("#number_" + chdata.id).html();
                var priceAll = p * n;
                if (p == "暂无票价") {
                    $("#amount_" + chdata.id).val("0");
                } else {
                    $("#amount_" + chdata.id).val(priceAll);
                }
                if ($(".ticket_choice").children("tr").length != "0") {
                    $("#remove_id").removeAttr("disabled");
                    $("#input_id").removeAttr("disabled");
                };
                $("#remove_id").click(function() {
                    $('input:checkbox').each(function() {
                        if ($(this).is(':checked') == true) {
                            $(this).parents("tr").remove();
                            if ($(".ticket_choice").children("tr").length == "0") {
                                $("#remove_id").attr('disabled', "true");
                            };
                            if ($(this).val() == "crp") {
                                $("#input_id").attr('disabled', "true");
                            }
                        }
                    });

                })


            }

        })(s);


        $("#input_id").click(function() {
            realname();
        });
        $(".pay-ticket").click(function() {
            add_ticket_table();

        });

    }
})

function toDecimal(num) {
    return num = num.toFixed(2)
}

function add_ticket_table() {
    var temp_html = "<table class='je-table'><thead><tr><td>票型</td><td>购买数量</td><td>金额</td></tr></thead><tbody class='ticket-info'></tbody></table><div class='je-form-item'>合计购买数量:<span class='numall'></span></div><div class='je-form-item'>应付金额:￥<span class='priceall'></span><div class='realbota'><input type='button' class='org_btn' id='paymoney' value='确认收费'></div></div>";
    jeBox.open({
        title: "确认出票",
        boxSize: ['60%', '40%'],
        content: temp_html,
        maskClose: false,
        closefun: function(index, id) {
            window.location.reload();
        }
    })
    var titemhtml = $("#ticket-info").html();
    var number_arr = [];
    var amount_arr = [];
    for (var i = 0; i < $(".ticket_choice tr").length; i++) {
        var tinfodata = {}
        tinfodata.id = $(".ticket_choice tr:eq(" + i + ") td:eq(0)").children("input").val();
        tinfodata.name = $(".ticket_choice tr:eq(" + i + ") td:eq(2)").children(".ticketname").val();
        tinfodata.number = $(".ticket_choice tr:eq(" + i + ") td:eq(4)").html();
        tinfodata.amount = $(".ticket_choice tr:eq(" + i + ") td:eq(5)").children(".amount").val();
        var conReg = /(?:\{)(\w*)(?:\})/g;
        var source = titemhtml.replace(conReg, function(node, key) {
            return tinfodata[key];
        });
        $(".ticket-info").append(source);
        number_arr.push(tinfodata.number);
        amount_arr.push(tinfodata.amount);
    }
    number_arr.forEach(function(item, index) {
        number_arr[index] = +item;
    });
    amount_arr.forEach(function(item, index) {
        amount_arr[index] = +item;
    });
    // console.log(number_arr[0] + ">>>")
    // console.log(amount_arr + ">>>>>")
    $(".numall").html(sum(number_arr));
    $(".priceall").html(toDecimal(sum(amount_arr)));
    $("#paymoney").click(function() {
        var pay = {}
        pay.numall = sum(number_arr);
        pay.priceall = toDecimal(sum(amount_arr));
        pay.peice = $(".priceall").html();
        pay.change = 0;
        var pay_html = "<div><div class='je-form-item'><label class='je-label je-f14'>总金额</label><div class='je-inputbox'><input type='text' name='title' autocomplete='off' class='je-input pay_money' readonly='readonly' value='" + pay.peice + "'></div></div><div class='je-form-item'><label class='je-label je-f14'>现金支付</label><div class='je-inputbox'><input type='number' name='title' autocomplete='off' value='" + pay.peice + "' class='je-input cash_money' min='0'></div></div><div class='je-form-item'><label class='je-label je-f14'>找零</label><div class='je-inputbox'><input type='text' name='title' autocomplete='off' value='" + pay.change + "' readonly='readonly' class='je-input change_money'></div></div></div>"
        var order_array = [];
        for (var t = 0; t < $(".ticket-info tr").length; t++) {
            var arr = {}
            arr.groupTicketId = $(".ticket-info tr:eq(" + t + ") td:eq(0)").html();
            arr.price = $(".ticket-info tr:eq(" + t + ") td:eq(3)").html();
            arr.number = $(".ticket-info tr:eq(" + t + ") td:eq(2)").html();
            console.log(arr)
            order_array.push(arr)
        }
        console.log(order_array)
        var pay_json = { "id": "1", "jsonrpc": "2.0", "method": "confirmSettlement", "params": { "order": { "sellerId": "1", "customerType": "1", "transactionTypeId": "1", "ifBooked": "0", "orderType": "0", "saleTypeId": "1", "ticketName": "", "number": pay.numall, "amount": pay.priceall, "state": "", "isDel": "0", "waterFlow": [{ "type": "1", "paymentTypeId": "0" }], "orderDetail": order_array, "settleState": "1", "source": "", "playdate": "" } } }
        console.log(pay_json)
        var paydata = $.ajax({
            type: "post",
            contentType: "application/json;charset=utf-8",
            url: "/api/ticketApi",
            dataType: "json",
            data: JSON.stringify(pay_json),
        });
        jeBox.open({
            title: "付款",
            boxSize: ['60%', '40%'],
            content: pay_html,
            maskClose: false,
            button: [{
                name: "确认收款",
                callback: function() {
                    paydata.then(function(data) {
                        if (data.result.code == 200) {
                            var ticket_code_html = $("#Ticket_temp").html()
                            for (var i = 0; i < data.result.body.orderDetail.length; i++) {
                                var codedata = data.result.body.orderDetail[i];
                                codedata.createTime = data.result.body.orderDetail[i].validateDate
                                codedata.valiTime = getvalitime(data.result.body.orderDetail[i].validateDate, data.result.body.orderDetail[i].validateDays)
                                codedata.ticket = data.result.body.orderDetail[i].code
                                codedata.price = tinfodata.amount
                                var conReg = /(?:\{)(\w*)(?:\})/g;
                                var source = ticket_code_html.replace(conReg, function(node, key) {
                                    return codedata[key];
                                });
                                $(".Ticket_temp").append(source)
                                    // console.log($("#code_" + codedata.id).html())
                                $("#code_" + codedata.id).qrcode({
                                    render: "table",
                                    width: 120,
                                    height: 120,
                                    text: codedata.id
                                })

                            }
                            $("#ticket_02").hide()
                            var temp_html = $("#ticket_02").html();
                            jeBox.open({
                                title: '打印票据',
                                boxSize: ["600px", "480px"],
                                content: temp_html,
                                maskLock: false,
                                btnAlign: "center",
                                button: [{
                                    name: '预览并打印',
                                    callback: function() {
                                        var LODOP;
                                        LODOP = getLodop();
                                        LODOP.PRINT_INIT("print_ticket");
                                        LODOP.ADD_PRINT_HTM("5.0mm", "5.0mm", "170mm", "80mm", $("#ticket_02").html());
                                        LODOP.PRINT_DESIGN()

                                    }
                                }],
                                closefun: function(index, id) {
                                    window.location.reload();
                                }
                            })
                        }
                    })
                }
            }],
            closefun: function(index, id) {
                window.location.reload();
            }
        });
        $(".cash_money").bind('input propertychange', function() {
            $(".change_money").val($(this).val() - pay.peice);
            $(".cash_money").keyup(function() {
                var reg = $(this).val().match(/\d+\.?\d{0,2}/);
                var txt = '';
                if (reg != null) {
                    txt = reg[0];
                }
                $(this).val(txt);
            }).change(function() {
                $(this).keypress();
                var v = $(this).val();
                if (/\.$/.test(v)) {
                    $(this).val(v.substr(0, v.length - 1));
                }
            });
        });
    })
}

function getprice(price) {
    if (price == undefined) {
        return "暂无票价"
    } else {
        return price;
    }
}

function getname(n) {
    if (n == null) {
        return "散票"
    } else {
        return n;
    }
}

function sum(arr) {
    var s = 0;
    if (arr.length == 0) {
        return 0;
    } else if (arr.length == 1) {
        return arr[0];
    } else {
        for (var i = 0; i < arr.length; i++) {
            s += arr[i];
        }
        return s;
    }
}

function getmoney(a) {
    var cash = $(".cash_money");
    cash.bind('input propertychange', function() {
        $('.change_money').val($(this).val());
    });
    // return cash - a;
}